<template>
	<div>
		<div>
			<Carousel v-model="carouselIndex" loop>
				<template  v-for="(item,index) in uploadList">
					<CarouselItem v-if="item.status === 'finished'">
						<div class="demo-upload-list">
							<img :src="item.url">
							<div class="demo-upload-list-cover">
								<Icon size="58" type="ios-create-outline" @click.native="handleView(item.name)"></Icon>
								<Icon size="58" type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
							</div>
						</div>
					</CarouselItem>
				</template>
			</Carousel>
		</div>
		<div>
			<Upload
				ref="upload"
				:show-upload-list="false"
				:default-file-list="defaultList"
				:on-success="handleSuccess"
				:format="['jpg','jpeg','png']"
				:max-size="2048"
				:on-format-error="handleFormatError"
				:on-exceeded-size="handleMaxSize"
				:before-upload="handleBeforeUpload"
				multiple
				type="drag"
				:action="uploadUrl"
				style="display: inline-block;width:58px;">
				<div style="width: 58px;height:58px;line-height: 58px;">
					<Icon type="md-add" size="20"></Icon>
				</div>
			</Upload>
		</div>

		<Modal ref="modal" title="保存内容" v-model="visible">
			<Form  :label-width="80">
				<FormItem label="标题">
					<Input v-model="formData.roll.title" placeholder="图片标题"></Input>
				</FormItem>
				<FormItem label="链接">
					<Input v-model="formData.roll.link" placeholder="图片链接"></Input>
				</FormItem>
				<FormItem>
					<Button @click="saveRollClick" type="primary">保存</Button>
					<Button @click="cancelClick" style="margin-left: 8px">取消</Button>
				</FormItem>
			</Form>
		</Modal>
	</div>
</template>
<script>
	import {FILE_UPLOAD_URL,deleteFileByPath} from '../../../api/file.js'
	import {getIndexRolls,addIndexRoll,updateIndexRoll,deleteIndexRoll} from '../../../api/indexroll.js'
    export default {
        data () {
            return {
				uploadUrl:FILE_UPLOAD_URL,
                defaultList: [],
                imgName: '',
                visible: false,
                uploadList: [],
				formData:{
					roll:{id:0,title:'',image:'',link:'',path:''}
				},
				//幻灯片索引
				carouselIndex:0
            }
        },
        methods: {
            handleView (name) {
                this.imgName = name;
                this.visible = true;
				//获取当前图像信息，并绑定表单数据
				let i = this.carouselIndex
				let file = this.uploadList[i]
				//有id属性，说明不是刚上传的图片，就是修改操作了
				if(file.id){
					this.formData.roll.id = file.id
					this.formData.roll.title = file.title
					this.formData.roll.link = file.link
					this.formData.roll.image = file.url
					this.formData.roll.path = file.path
				}else{
					//add
					this.formData.roll.id = 0
					this.formData.roll.title = ''
					this.formData.roll.image = file.url
					this.formData.roll.path = file.name
					this.formData.roll.link = ''
				}
				this.$nextTick(function() {
					this.$refs.modal.footerHide = true;
				})
            },
            handleRemove (file) {
				this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确定要删除该轮播图吗？</p>',
                    onOk: () => {
						//删除内容,如果没有id，说明只是图片，删除图片就行
						if(file.id){
							deleteIndexRoll(file.id).then(res=>{
								if(res.data.status.code == 2000){
									const fileList = this.uploadList;
									this.uploadList.splice(fileList.indexOf(file), 1);
									//删除服务器图片
									deleteFileByPath(file.name).then(res => {
										if(res.data.status.code == 2000){
                      console.log("delete file .")
										}
									}).catch(err => {
										console.log(err)
									})
								}
							}).catch(err => {
								console.log(err)
							})
						}else{
							const fileList = this.uploadList;
							this.uploadList.splice(fileList.indexOf(file), 1);
							//删除服务器图片
							deleteFileByPath(file.name).then(res => {
								if(res.data.status.code == 2000){
                  console.log("delete file .")
								}
							}).catch(err => {
								console.log(err)
							})
						}
					}
                });
            },
            handleSuccess (res, file) {
				if(res.status.code == 2000){
					file.url = res.data.url
					file.name = res.data.path
					//轮播图选择当前新增的图片
					this.carouselIndex = this.$refs.upload.fileList.length-1
				}
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: 'The file format is incorrect',
                    desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
                });
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: 'Exceeding file size limit',
                    desc: 'File  ' + file.name + ' is too large, no more than 2M.'
                });
            },
            handleBeforeUpload () {
                const check = this.uploadList.length < 5;
                if (!check) {
                    this.$Notice.warning({
                        title: 'Up to five pictures can be uploaded.'
                    });
                }
                return check;
            },
			cancelClick(){
				this.visible = false
			},
			saveRollClick(){
				//根据当前roll对象的id是否为0，判断是新增还是修改
				if(this.formData.roll.id == 0){
					//add
					addIndexRoll(this.formData.roll).then(res=>{
						//更新客户端数据
						this.uploadList[this.carouselIndex].id= res.data.data.id
						this.uploadList[this.carouselIndex].title= res.data.data.title
						this.uploadList[this.carouselIndex].link= res.data.data.link
						this.visible = false
					}).catch(err=>{console.log(err)})
				}else{
					//update
					let roll = {}
					roll.id = this.formData.roll.id
					roll.title = this.formData.roll.title
					roll.link =this.formData.roll.link
					updateIndexRoll(roll).then(res=>{
						if(res.data.status.code == 2000){
							//更新uploadList
							this.uploadList[this.carouselIndex].title = this.formData.roll.title
							this.uploadList[this.carouselIndex].link = this.formData.roll.link
							this.visible=false
						}
					}).catch(err=>{console.log(err)})
				}
			}
        },
        mounted () {
			getIndexRolls().then(res=>{
				if(res.data.status.code == 2000){
					for(let i=0; i<res.data.data.length;i++){
						let d = res.data.data[i]
						let roll = {"id":d.id,"title":d.title,"url":d.image,"name":d.path,"link":d.link,
						"status":"finished","percentage":0,"showProgress":true,"response":{}}
						//this.defaultList.push(roll)
						this.$refs.upload.fileList.push(roll)
					}
				}
				this.uploadList = this.$refs.upload.fileList;
			}).catch(err=>{
				console.log(err)
				this.uploadList = this.$refs.upload.fileList;
			})
        }
    }
</script>
<style>
    .demo-upload-list{
        display: inline-block;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height:normal;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
